<template>
  <div class="company-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span>公司管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">添加公司</el-button>
      </div>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="公司名称">
          <el-input v-model="searchForm.name" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="companyList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="180"></el-table-column>
        <el-table-column prop="name" label="公司名称" width="200"></el-table-column>
        <el-table-column prop="address" label="公司地址"></el-table-column>
        <el-table-column label="公司头像" width="100">
          <template slot-scope="scope">
            <el-image :src="scope.row.avatar" style="width: 50px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="page.currPage" :page-sizes="[10, 20, 30, 50]" :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑公司弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="公司头像">
          <MyUpload ref="childUpload" @callParent="transDownloadUrl"></MyUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCompanyList, getCompanySubmit, delCompany } from '@/api'
import MyUpload from '@/components/upload';

export default {
  components: {
    MyUpload
  },
  name: 'CompanyManagement',
  data() {
    return {
      searchForm: {
        name: '',
        status: ''
      },
      companyList: [],
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '添加公司',
      form: {
        id: '',
        name: '',
        address: '',
        contact: '',
        phone: '',
        email: '',
        status: '1',
        description: '',
        avatar: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入公司名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入公司地址', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      page: {
        currPage: 1,
        pageSize: 10
      },
      total: 0
    }
  },
  created() {
    this.getCompanyList()
  },
  methods: {
    transDownloadUrl(url) {
      this.form.avatar = url;
    },
    async getCompanyList() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          ...this.page
        }
        const res = await getCompanyList(params)
        if (res.code === 200) {
          this.companyList = res.data.list || []
          this.total = parseInt(res.data.total) || 0
        } else {
          this.$message.error(res.msg || '获取公司列表失败')
        }
      } catch (error) {
        console.error('获取公司列表出错:', error)
        this.$message.error('获取公司列表出错')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.page.currPage = 1
      this.getCompanyList()
    },
    resetSearch() {
      this.searchForm = {
        name: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.getCompanyList()
    },
    handleCurrentChange(val) {
      this.page.currPage = val
      this.getCompanyList()
    },
    handleAdd() {
      this.dialogTitle = '添加公司'
      this.form = {
        id: '',
        name: '',
        address: '',
        contact: '',
        phone: '',
        email: '',
        status: '1',
        description: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑公司'
      this.form = { ...row }
      this.$nextTick(() => {
        this.$refs.childUpload.setImgUrl(this.form.avatar);
      })
      this.dialogVisible = true
    },
    handleDelete(row) {
      this.$confirm('确认删除该公司吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await delCompany(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getCompanyList()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除公司出错:', error)
          this.$message.error('删除公司出错')
        }
      }).catch(() => {
      })
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            const res = await getCompanySubmit(this.form)
            if (res.code === 200) {
              this.$message.success(this.form.id ? '编辑成功' : '添加成功')
              this.dialogVisible = false
              this.getCompanyList()
            } else {
              this.$message.error(res.msg || (this.form.id ? '编辑失败' : '添加失败'))
            }
          } catch (error) {
            console.error('提交表单出错:', error)
            this.$message.error('提交表单出错')
          } finally {
            this.submitLoading = false
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.company-management {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>